import { createStore, combineReducers } from 'redux';
import userReducer, { UserState } from './user/reducer'; 
import languageReducer, { LanguageState } from './language/reducer';

import { configureStore } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';

const isValidKey = (key: string): boolean => {
  const keyRegex = /^[a-zA-Z0-9._-]+$/;
  return keyRegex.test(key);
};

const createAsyncStorage = () => {
  return {
    getItem: async (key: string) => {
      return AsyncStorage.getItem(key);
    },
    setItem: async (key: string, value: string) => {
      return AsyncStorage.setItem(key, value);
    },
    removeItem: async (key: string) => {
      return AsyncStorage.removeItem(key);
    },
  };
};

const persistConfig = {
  // Change the key to a valid format
  key: 'persist_root',
  storage: createAsyncStorage(),
};

// Combine multiple reducers
const rootReducer = combineReducers<RootState>({
  user: userReducer as any,
  language: languageReducer as any,
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store:any = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }),
});

// Define the root state type of the application
export interface RootState {
  user: UserState;
  language: LanguageState;
}
export const persistor = persistStore(store);
export default store;
